/**
 * Created by Alice on 2016/9/13 0013
 */
;-function (window) {
    "use strict";
    //TODO 预设变量写这里，全局变量写在base.js 里面 使用 r. 调用
    var ready = {
        layer: null,
        judge: [],
        judge_name: [],
        courtrooms: [],
        courtrooms_name: [],
        page_size: 12,
        init_date:null,
        dept: [],
        dept_name: [],
        now_judge: [],
        now_judge_name: []
    };
    //TODO 初始化的方法写这里面
    var init = function () {
        init_ready();//加载预设变量

        var currentDay = utils.get_date(0);
        //查询的开始时间默认给今天
        $('#startTime').datetimepicker({
            bootcssVer: 3,
            minView: "month", //选择日期后，不会再跳转去选择时分秒
            weekStart: "1",
            format: "yyyy-mm-dd", //选择日期后，文本框显示的日期格式
            language: 'zh-CN', //汉化
            autoclose: true //选择日期后自动关闭
        }).on('changeDate', function (ev) {
            console.log(ev.date.valueOf());
        });
        $('#endTime').datetimepicker({
            bootcssVer: 3,
            minView: "month", //选择日期后，不会再跳转去选择时分秒
            weekStart: "1",
            format: "yyyy-mm-dd", //选择日期后，文本框显示的日期格式
            language: 'zh-CN', //汉化
            autoclose: true //选择日期后自动关闭
        }).on('changeDate', function (ev) {
            console.log(ev.date.valueOf());
        });

        init_event();
        function init_event() {//TODO 初始化页面事件
            $("#startTime").find("input").val(currentDay);
            $("#endTime").find("input").val(currentDay);
            Class.select_all_group();
            Class.select_all_judges();
            Class.init_push();
            $("#conditionBtn").click(function () {
                $("#loading").show();
                Class.count_case();
            });
        }

        function init_ready() {//TODO 初始化预设值
            layui.use('layer', function () {
                ready.layer = layui.layer;
            });
            var judge_id = utils.get_url_param("judge");
            judge_id ? ready.judge.push(judge_id) : '';
            var courtroom_id = utils.get_url_param("courtroom_id");
            courtroom_id ? ready.courtrooms.push(courtroom_id) : '';
        }
    };
    //TODO 内部调用的方法写这里
    var Class = {
        select_all_group: function () {
            $.get(r.base_path + 'archives/selectAllDepartment', {
                courtId: r.court_id
            }, function (result) {
                $('#loading').hide();
                if (result && result.status == 0) {
                    ready.init_data = result.data;
                    var dropmenu_judge = $('#dropmenu_dept').empty();
                    dropmenu_judge.append('<option value="" selected>所有部门</option>');
                    if (result.data) {
                        $.each(result.data, function (index, dept) {
                            ready.dept.push(dept.uid);
                            ready.dept_name.push(dept.deptname);
                            dropmenu_judge.append('<option value="' + dept.uid + '" >' + dept.deptname + '</option>');
                            // dropmenu_dept.append('<li><a href="javascript:;" onclick="p.dept_change(\'' + dept.uid + '\')">' + dept.deptname + '</a></li>');
                        })
                    }
                }
            }, 'json');
        },
        select_all_judges: function () {
            $.get(r.base_path + 'archives/selectArchivesInfo', {
                courtId: r.court_id
            }, function (result) {
                if (result && result.status == 0) {
                    ready.init_data = result.data
                    var dropmenu_judge = $('#allJudges').empty();
                    dropmenu_judge.append('<option value="" selected>所有法官</option>');
                    var dropmenu_courtroom = $('#allCourtRooms').empty();
                    dropmenu_courtroom.append('<option value="" selected>所有法庭</option>');
                    var dropmenu_secretary = $("#allSecretary").empty();
                    dropmenu_secretary.append('<option value="" selected>所有书记员</option>');
                    if (result.data && result.data.dept) {
                        $.each(result.data.dept, function (index, dept) {
                            dropmenu_judge.append('<option value="' + dept.userId + '" >' + dept.username + '</option>');
                            ready.judge.push(dept.userId);
                            ready.judge_name.push(dept.username);
                            ready.now_judge.push(dept.userId);
                            ready.now_judge_name.push(dept.username);
                        })
                    }
                    if (result.data && result.data.deptAnSecretaries) {

                            $.each(result.data.deptAnSecretaries, function (secretarie_no, secretarie) {
                                dropmenu_secretary.append("<option value='" + secretarie.userId + "'>" + secretarie.username + "</option>");
                            });

                    }
                    if (result.data && result.data.courtroom) {
                        $.each(result.data.courtroom, function (index, courtroom) {
                            // dropmenu_courtroom.append('<li><a href="javascript:;" onclick="p.courtroom_change(\'' + courtroom.uid + '\')">' + courtroom.courtroomname + '</a></li>');
                            dropmenu_courtroom.append('<option value="' + courtroom.uid + '" >' + courtroom.courtroomname + '</option>');
                            ready.courtrooms.push(courtroom.uid);
                            ready.courtrooms_name.push(courtroom.courtroomname);
                        })
                    } else {
                        $('#allCourtRooms').html('无法庭');
                    }
                    //加载数据
                    Class.count_case();
                    Class.select_case_type();
                    // Class.select_secretary();
                }
            }, 'json');
        },
        dept_change: function (dept_uid) {
            // console.info(ready.init_data.dept);
            // console.info(dept_uid);
            ready.now_judge = [];
            ready.now_judge_name = [];
            var dropmenu_judge = $('#allJudges').empty();
            dropmenu_judge.append('<option value="" selected>所有法官</option>');
            var dropmenu_secretary = $("#allSecretary").empty();
            dropmenu_secretary.append('<option value="" selected>所有书记员</option>');
            // dropmenu_judge.append('<li><a href="javascript:;" onclick="p.judge_change(\'sometimes_everything_is_ok\')">所有法官</a></li>');
            // $('#dropmenu_judge').find('a').eq(0).html('所有法官 <span class="caret"></span>');
            if (dept_uid==''){
                $.each(ready.init_data.dept, function (index, dept) {
                    dropmenu_judge.append('<option value="' + dept.userId + '" >' + dept.username + '</option>');
                    // dropmenu_judge.append('<li><a href="javascript:;" onclick="p.judge_change(\'' + dept.userId + '\')">' + dept.username + '</a></li>');
                    ready.now_judge.push(dept.userId);
                    ready.now_judge_name.push(dept.username);
                });
                //书记员下拉框
                $.each(ready.init_data.deptAnSecretaries, function (index, secretarie) {
                    dropmenu_secretary.append('<option value="' + secretarie.userId + '" >' + secretarie.username + '</option>');
                })
            }else {
                // var dept_no = ready.dept.indexOf(dept_uid);
                // $('#dropmenu_dept').find('a').eq(0).html(ready.dept_name[dept_no] + ' <span class="caret"></span>');
                $.each(ready.init_data.dept, function (index, dept) {
                    if (dept.deptId == dept_uid) {
                        dropmenu_judge.append('<option value="' + dept.userId + '" >' + dept.username + '</option>');
                        ready.now_judge.push(dept.userId);
                        ready.now_judge_name.push(dept.username);
                    }
                });
                //书记员下拉框
                $.each(ready.init_data.deptAnSecretaries, function (index, secretarie) {
                    if (secretarie.deptId == dept_uid) {
                        dropmenu_secretary.append('<option value="' + secretarie.userId + '" >' + secretarie.username + '</option>');
                    }
                });
            }
        },
        select_case_type: function () {
            $.get(r.base_path + "trial/selectAllCaseType", {courtId: ready.city}, function (result) {
                if (result.data) {
                    var case_type = $("#caseTypeName").empty();
                    if (null != ready.case_type && '' != ready.case_type && 'null' != ready.case_type) {
                        $.each(result.data, function (i, valueOfElement) {
                            if (ready.case_type == valueOfElement.uid) {
                                case_type.append("<option value='" + valueOfElement.uid + "'>" + valueOfElement.name + "</option>");
                            }
                        });
                    } else {
                        case_type.append("<option value=''>" + "所有类型" + "</option>");
                        $.each(result.data, function (i, valueOfElement) {
                            case_type.append("<option value='" + valueOfElement.uid + "'>" + valueOfElement.name + "</option>");
                        });
                    }
                }
            }, 'json');
        },
        select_secretary: function () {
            var select_secretary = $("#allSecretary").empty();
            $.get(r.base_path + "trial/selectAllSecretaries", {
                courtId: r.court_id
            }, function (result) {
                if (result.data) {
                    select_secretary.append("<option value=''>" + "所有书记员" + "</option>");
                    $.each(result.data, function (i, valueOfElement) {
                        select_secretary.append("<option value='" + valueOfElement.uid + "'>" + valueOfElement.username + "</option>");
                    });
                }
            }, 'json');
        },

        count_case: function () {
            var caseno = $("#caseno").val();
            var caseName = $("#caseName").val();
            var caseTypeName = $("#caseTypeName").val();
            var courtRoom = $("#allCourtRooms").val();
            var  deptId =$("#dropmenu_dept").val();
            var  judgeIds=[];
            if ( $("#allJudges option:selected").val() ==  '') {
                $("#allJudges option").each(function(){  //遍历所有option
                    var judgeId = $(this).val();   //获取option值
                    if(judgeId!=''){
                        judgeIds.push(judgeId);  //添加到数组中
                    }
                });
            } else {
                judgeIds.push($("#allJudges option:selected").val());
            };
            var  secretarys=[];
            if ( $("#allSecretary option:selected").val() ==  '') {
                $("#allSecretary option").each(function(){  //遍历所有option
                    var st = $(this).val();   //获取option值
                    if(st!=''){
                        secretarys.push(st);  //添加到数组中
                    }
                });
            } else {
                secretarys.push($("#allSecretary option:selected").val());
            };
            // var secretary = ready.secretary || $("#allSecretary").val();
            var startTime = $("#startTime").find("input").val();
            var endTime = $("#endTime").find("input").val();
            // console.log(caseName, caseTypeName, courtRoom, judge, secretary, startTime, endTime);
            $.ajax({
                url: r.base_path + "archives/findCountDeptScheduleOrReviewCase",
                type: "get",
                dataType: "json",
                data: {
                    deptId:deptId,
                    caseno: caseno,
                    caseName: caseName,
                    caseTypeName: caseTypeName,
                    courtRoomId: courtRoom,
                    judgeList: judgeIds.toString(),
                    secretaryList: secretarys.toString(),
                    startDate: startTime,
                    endDate: endTime,
                    courtId: r.court_id,
                    status: 0
                },
                success: function (result) {
                    // console.log(result.data);
                    var s = result.data;
                    if (s == 0) {
                        Class.page(1, 1, null);
                    } else {
                        Class.page(1, Math.ceil(s / 12), Class.get_case);
                    }
                    Class.get_case(1);
                }
            }).fail(function () {
                $('#loading').hide();
            });
        },
        get_case: function (page) {
            var caseno = $("#caseno").val();
            var caseName = $("#caseName").val();
            var caseTypeName = $("#caseTypeName").val();
            var courtRoom = $("#allCourtRooms").val();
            var  deptId =$("#dropmenu_dept").val();
            var  judgeIds=[];
            if ( $("#allJudges option:selected").val() ==  '') {
                $("#allJudges option").each(function(){  //遍历所有option
                    var judgeId = $(this).val();   //获取option值
                    if(judgeId!=''){
                        judgeIds.push(judgeId);  //添加到数组中
                    }
                });
            } else {
                judgeIds.push($("#allJudges option:selected").val());
            }
            var  secretarys=[];
            if ( $("#allSecretary option:selected").val() ==  '') {
                $("#allSecretary option").each(function(){  //遍历所有option
                    var st = $(this).val();   //获取option值
                    if(st!=''){
                        secretarys.push(st);  //添加到数组中
                    }
                });
            } else {
                secretarys.push($("#allSecretary option:selected").val());
            };
            // var secretary = ready.secretary || $("#allSecretary").val();
            var startTime = $("#startTime").find("input").val();
            var endTime = $("#endTime").find("input").val();
            // console.log(caseName, caseTypeName, courtRoom, judge, secretary, startTime, endTime);
            var row_no_padding = $(".row-no-padding").empty();
            $.ajax({
                url: r.base_path + "archives/findAlleptScheduleOrReviewCase",
                type: "post",
                dataType: "json",
                data: {
                    deptId:deptId,
                    caseno: caseno,
                    caseName: caseName,
                    caseTypeName: caseTypeName,
                    courtRoomId: courtRoom,
                    judgeList: judgeIds.toString(),
                    secretaryList: secretarys.toString(),
                    startDate: startTime,
                    endDate: endTime,
                    page: page,
                    pageSize: ready.page_size,
                    courtId: r.court_id,
                    status: 0
                },
                success: function (result) {
                    // console.log(result);
                    //清空表格
                    if (result.status == 0) {
                        if (result.data.length == 0) {
                            row_no_padding.append('<span>暂无开庭信息</span>');
                        } else {
                            var picNum = 6;
                            $.each(result.data, function (i, valueOfElement) {
                                var caseName = valueOfElement.casename;
                                var startDate = valueOfElement.start_date;
                                var uid = valueOfElement.uid;
                                if (startDate) {
                                    startDate = startDate.substring(0, startDate.length - 2);
                                }
                                var status = valueOfElement.status;
                                var courtroom_name = valueOfElement.courtroom_name;
                                var cid = valueOfElement.courtroom_id;
                                var statusName = "";
                                if (0 == status) {
                                    statusName = "排期";
                                } else if (1 == status) {
                                    statusName = "开庭";
                                } else if (2 == status) {
                                    statusName = "休庭";
                                } else if (3 == status) {
                                    statusName = "闭庭";
                                } else {
                                    statusName = "归档";
                                }
                                var randomNum = parseInt(picNum * Math.random() + 1);//随机出1到picNum的整数
                                var href = r.base_path + "views/archives/living.html?uid=" + uid + "&cid=" + cid + "&vc=" + valueOfElement.courtId;
                                var html = '<div class="col-md-2 col-xs-6">' +
                                    '<div class="more-courting-item">' +
                                    '<a href="' + href + '">' +
                                    '<div class="more-courting-item-img-panel">' +
                                    '<p class="more-courting-item-img-panel-top">' + (courtroom_name ? courtroom_name : '未知') + '</p>' +
                                    '<img src="' + r.base_path + "assets/img/more_court_test" + randomNum + ".jpg" + '" alt="法院">' +
                                    '<p class="more-courting-item-img-panel-bottom" >' + statusName + '</p>' +
                                    '</div>' +
                                    '<p id="startDate">' + startDate + '</p>' +
                                    '<p id="caseNoDis">' + (valueOfElement.caseno ? valueOfElement.caseno : '未知') + '</p>' +
                                    '<p class="more-courting-item-depiction">' +
                                    '<i class="fa fa-exchange cursor-hand" title="推送" id="' + valueOfElement.uid + '"></i>' +
                                    '<span>' + (caseName ? caseName : "&nbsp;") + '</span>' +
                                    '</p>' +
                                    '</a>' +
                                    '</div>' +
                                    '</div>';
                                row_no_padding.append(html);
                            });
                            $('.fa-exchange').click(function (e) {
                                e.preventDefault();
                                // console.log();
                                $('#_uid').val(this.id);
                                $("#_detail").modal("show");
                            })
                        }
                        $("#loading").hide();
                        row_no_padding.show();
                    } else {
                        $("#loading").hide();
                        row_no_padding.append('<span>'+result.msg+'</span>');
                    }

                },
                error: function () {
                    $("#loading").hide();
                }
            });
        },
        init_push: function () {
            var court_push = $("#_courtPush").empty();
            $(r.court_list).each(function (i, n) {
                court_push.append("<option value='" + n.courtid + "'>" + n.courtname + "</option>");
            });
            Class.select_courtroom(r.court_list[0].courtid);
            court_push.change(function () {
                var val = $(this).children('option:selected').val();
                Class.select_courtroom(val);
            })
        },
        select_courtroom: function (id) {
            $.post(r.base_path + "sys/courtEquipment/selectCourtRoom", {courtId: id}, function (result) {
                if (result.data) {
                    $("#_courtRoom").empty();
                    $.each(result.data, function (i, n) {
                        $("#_courtRoom").append("<option value='" + n.uid + "'>" + n.courtroomname + "</option>");
                    });
                }
            }, 'json')
        },
        save: function () {
            layui.use('layer', function () {
                var layer = layui.layer;
                layer.confirm('想要推送该案件吗?<br>将要推送到:<br>"' +
                    $('#_courtPush').find("option:selected").text() + '<br>' + $('#_courtRoom').find("option:selected").text() + '"', {
                    btn: ['是的', '取消'] //按钮
                }, function () {
                    $.post(r.base_path + "planTransfer/planTransferDown", {
                        planid: $('#_uid').val(),
                        downcourtid: $('#_courtPush').val(),
                        courtroomid: $('#_courtRoom').val()
                    }, function (result) {
                        if (result && result.status == 0) {
                            layer.msg('推送成功！');
                        } else {
                            layer.msg(result.msg);
                        }
                        $("#_detail").modal("hide");
                    }, 'json').fail(function () {
                        $("#_detail").modal("hide");
                    })
                }, function () {

                });
            });
        },
        page: function (now, totalPages, callback) {
            base.pagination('#_page', {
                currentPage: now,
                totalPages: totalPages,
                onPageClicked: function (page) {
                    callback(page);
                }
            });
        }

    };
    init();
    //TODO 对外公开的方法写在这里
    window.p = {
        save: Class.save,
        dept_change:Class.dept_change
    };
}(window);